//
//  KAAlertView.swift
//  kano
//
//  Created by Sophia on 2024/8/19.
//

import UIKit
import ActiveLabel

class KAAlertAction {
    var titleColor: UIColor
    var title: String?
    var backgroundColor: UIColor
    var attributedTitle: NSAttributedString?
    var handler: ((KAAlertAction) -> Void)?
    
    init(title: String? = nil, titleColor: UIColor, backgroundColor: UIColor = .clear, handler: ((KAAlertAction) -> Void)? = nil) {
        self.title = title
        self.titleColor = titleColor
        self.backgroundColor = backgroundColor
        self.handler = handler
    }
    
    init(attributedTitle: NSAttributedString, titleColor: UIColor, backgroundColor: UIColor = .clear, handler: ((KAAlertAction) -> Void)? = nil) {
        self.attributedTitle = attributedTitle
        self.titleColor = titleColor
        self.backgroundColor = backgroundColor
        self.handler = handler
        self.title = attributedTitle.string
    }
}


class KAAlertView: UIView {

    private lazy var titleLabel: UILabel = {
        titleLabel = UILabel()
        titleLabel.textColor = .black
        titleLabel.textAlignment = .center
        titleLabel.font = UIFont.boldSystemFont(ofSize: kscale(16))
        titleLabel.numberOfLines = 0
        return titleLabel
    }()
    private lazy var subLabel: ActiveLabel = {
        subLabel = ActiveLabel()
        subLabel.numberOfLines = 0
        return subLabel
    }()
    private lazy var closeButton: UIButton = {
        closeButton = UIButton()
        closeButton.isHidden = true
        closeButton.frame = CGRectMake(self.width-kscale(30), kscale(5), kscale(24), kscale(24));
        closeButton.setBackgroundImage(UIImage(named: "common_close"), for: .normal)
        closeButton.addTarget(self, action: #selector(dismissAlert), for: .touchUpInside)
        return closeButton
    }()
    private lazy var bgView: UIView = {
        bgView = UIView(frame: UIScreen.main.bounds)
        bgView.backgroundColor = UIColor.ka_hexColor(0x00000, alphaVaule: 0.36)
        return bgView
    }()
    private var horizontalLine : UIView = {
        let horizontalLine = UIView()
        horizontalLine.backgroundColor = .color77777D
        return horizontalLine
    }()
    private var actionArray: [KAAlertAction] = []
    private var buttonHeight: CGFloat {
        get {
            actionArray.count > 0 ? 50 : 0
        }
    }
    private var titleText: String?
    private var subtitleText: String?
    private var clickTitle: String?
    private var clickSecond: String?
    private var clickHandler: ((String) -> Void)?

    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupView()
    }
    
    private func setupView() {
        backgroundColor = .white
        self.frame = CGRectMake(0, 0, kscale(270), kscale(150));
        addSubview(titleLabel)
        addSubview(subLabel)
        addSubview(closeButton)
    }
    
    func addAction(_ action: KAAlertAction) {
        actionArray.append(action)
    }
    
    // Method to show alert view
    func show() {
        var aSuperView = UIViewController.ka_current().view
        if aSuperView == nil {
            aSuperView = UIViewController.ka_current().view
        }
        if let superView = aSuperView {
            doShowAlert(to: superView)
        }
    }
    
    func showOnWindow() {
        var aSuperView = UIViewController.ka_tabVC()?.view
        if aSuperView == nil {
            aSuperView = UIViewController.ka_current().view
        }
        if let superView = aSuperView {
            doShowAlert(to: superView)
        }
    }
}

//class method
extension KAAlertView {
    static func alert(withTitle title: String?, subtitle: String?, clickTitle: String = "", clickSecond: String = "", click: @escaping (String) -> Void) -> KAAlertView {
        let alertView = KAAlertView()
        alertView.titleText = title
        alertView.subtitleText = subtitle
        alertView.clickTitle = clickTitle
        alertView.clickSecond = clickSecond
        alertView.clickHandler = click
        alertView.titleLabel.text = title
        

        let customType = ActiveType.custom(pattern: clickTitle)
        let customType1 = ActiveType.custom(pattern: clickSecond)
        alertView.subLabel.enabledTypes = [customType,customType1]
        alertView.subLabel.customColor[customType] = .themeColor
        alertView.subLabel.customColor[customType1] = .themeColor
        alertView.subLabel.handleCustomTap(for: customType, handler: { (customType) in
            alertView.clickHandler!(customType)
        })
        alertView.subLabel.handleCustomTap(for: customType1, handler: { (customType) in
           
        })
        alertView.subLabel.text = subtitle
        alertView.subLabel.numberOfLines = 0
        alertView.subLabel.font = kFontSize(12)
        alertView.subLabel.textColor = .color8A8891
        return alertView
    }
    
    static func alert(withTitle title: String?, attributedSubtitle: NSAttributedString) -> KAAlertView {
        let alertView = KAAlertView()
        alertView.titleText = title
        alertView.subtitleText = attributedSubtitle.string
        alertView.titleLabel.text = title
        alertView.subLabel.attributedText = attributedSubtitle
        return alertView
    }
}

// show method
extension KAAlertView {
    // Method to show alert to a specified super view
    private func doShowAlert(to superView: UIView) {
        let leftMargin: CGFloat = kscale(20)
        let labelW = width - 2 * leftMargin
        let topMargin: CGFloat = kscale(15)
        let padding: CGFloat = kscale(10)
        
        if !titleText!.isEmpty, !subtitleText!.isEmpty {
            let maxSize = CGSize(width: labelW, height: .greatestFiniteMagnitude)
            let mTitleLabelH = titleLabel.sizeThatFits(maxSize).height
            titleLabel.frame = CGRect(x: leftMargin, y: topMargin, width: labelW, height: mTitleLabelH)
            let aSubLabelH = subLabel.sizeThatFits(maxSize).height
            subLabel.frame = CGRect(x: leftMargin, y: titleLabel.frame.maxY + padding, width: labelW, height: aSubLabelH)
            frame = CGRect(x: 0, y: 0, width: kscale(270), height: subLabel.bottom + padding + buttonHeight)
        }
        if titleText!.isEmpty {
            let maxSize = CGSize(width: labelW, height: .greatestFiniteMagnitude)
            let aSubLabelH = subLabel.sizeThatFits(maxSize).height
            subLabel.frame = CGRect(x: leftMargin, y: leftMargin, width: labelW, height: aSubLabelH)
            frame = CGRect(x: 0, y: 0, width: kscale(270), height: subLabel.bottom + padding + buttonHeight)
        }
        if subtitleText!.isEmpty {
            let maxSize = CGSize(width: labelW, height: .greatestFiniteMagnitude)
            let mTitleLabelH = titleLabel.sizeThatFits(maxSize).height
            titleLabel.frame = CGRect(x: leftMargin, y: leftMargin, width: labelW, height: mTitleLabelH)
            frame = CGRect(x: 0, y: 0, width: kscale(270), height: titleLabel.bottom + padding + buttonHeight)
        }
        
        ka_addCorner(withRadius: kscale(10))
        center = CGPoint(x: UIScreen.main.bounds.width / 2, y: UIScreen.main.bounds.height / 2)
        
        horizontalLine.frame = CGRect(x: 0, y: height - buttonHeight - 1, width: width, height: 1 / UIScreen.main.scale)
        addSubview(horizontalLine)
        
        let btnW = width / CGFloat(actionArray.count)
        var lineArray: [UIView] = []
        for (i, action) in actionArray.enumerated() {
            let aBtn = UIButton()
            aBtn.setTitle(action.title, for: .normal)
            aBtn.setTitleColor(action.titleColor, for: .normal)
            aBtn.backgroundColor = action.backgroundColor
            aBtn.titleLabel?.font = UIFont.systemFont(ofSize: kscale(14))
            aBtn.titleLabel?.numberOfLines = 0
            aBtn.sizeToFit()
            aBtn.tag = i
            aBtn.frame = CGRect(x: CGFloat(i) * btnW, y: height - buttonHeight, width: btnW, height: buttonHeight)
            aBtn.addTarget(self, action: #selector(doBtnClickAction(_:)), for: .touchUpInside)
            addSubview(aBtn)
            if i < actionArray.count - 1 {
                let aLine = UIView(frame: CGRect(x: 0, y: aBtn.frame.minY, width: 1 / UIScreen.main.scale, height: buttonHeight))
                aLine.center.x = aBtn.frame.maxX
                aLine.backgroundColor = .color77777D
                addSubview(aLine)
                lineArray.append(aLine)
            }
        }
        
        lineArray.forEach { bringSubviewToFront($0) }
        
        superView.addSubview(bgView)
        superView.addSubview(self)
        bgView.alpha = 0
        alpha = 0
        UIView.animate(withDuration: 0.3) {
            self.bgView.alpha = 1
            self.alpha = 1
        }
    }
    
    func showInView(_ superview: UIView) {
        self.frame = CGRect(x: 0, y: 0, width: 270, height: 150)
        self.center = superview.center
        self.layer.cornerRadius = 10
        self.clipsToBounds = true
        
        let horizontalLine = UIView(frame: CGRect(x: 0, y: self.bounds.height - buttonHeight - 1, width: self.bounds.width, height: 1 / UIScreen.main.scale))
        horizontalLine.backgroundColor = UIColor(red: 48/255, green: 50/255, blue: 62/255, alpha: 1)
        addSubview(horizontalLine)
        
        let buttonWidth = self.bounds.width / CGFloat(actionArray.count)
        for (index, action) in actionArray.enumerated() {
            let button = UIButton(frame: CGRect(x: CGFloat(index) * buttonWidth, y: self.bounds.height - buttonHeight, width: buttonWidth, height: buttonHeight))
            button.setTitle(action.title, for: .normal)
            button.setTitleColor(action.titleColor, for: .normal)
            button.backgroundColor = action.backgroundColor
            button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
            button.tag = index
            button.addTarget(self, action: #selector(buttonClicked(_:)), for: .touchUpInside)
            addSubview(button)
            
            if index < actionArray.count - 1 {
                let line = UIView(frame: CGRect(x: button.frame.maxX, y: button.frame.minY, width: 1 / UIScreen.main.scale, height: buttonHeight))
                line.backgroundColor = UIColor(red: 48/255, green: 50/255, blue: 62/255, alpha: 1)
                addSubview(line)
            }
        }
        
        superview.addSubview(self)
        self.alpha = 0
        UIView.animate(withDuration: 0.3) {
            self.alpha = 1
        }
    }
    
    // Method to show alert view to current view
    func doShowAlertToCurrentView() {
        var aSuperView = UIViewController.ka_currentNavigationController().topViewController?.view
        if aSuperView == nil {
            aSuperView = UIViewController.ka_current().view
        }
        if let superView = aSuperView {
            doShowAlert(to: superView)
        }
    }
}

// dismiss method
extension KAAlertView {
    @objc private func dismissAlert() {
        UIView.animate(withDuration: 0.3, animations: {
            self.alpha = 0
        }) { _ in
            self.removeFromSuperview()
        }
    }
    
    static func dismissAllAlerts() {
        for window in UIApplication.shared.windows {
            for view in window.subviews where view is KAAlertView {
                (view as? KAAlertView)?.dismissAlert()
            }
        }
    }
    
    // Method to dismiss the alert view
    private func doDismissAlertView() {
        UIView.animate(withDuration: 0.3, animations: {
            self.bgView.alpha = 0
            self.alpha = 0
        }) { _ in
            self.removeFromSuperview()
            self.bgView.removeFromSuperview()
        }
    }
    
    @objc private func buttonClicked(_ sender: UIButton) {
        let action = actionArray[sender.tag]
        action.handler?(action)
        dismissAlert()
    }
    
    @objc private func doBtnClickAction(_ sender: UIButton) {
        let action = actionArray[sender.tag]
        action.handler?(action)
        doDismissAlertView()
    }
}
